package com.way.util;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class BeanUtil {

    public static  <T> T beanToJson(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public static Map<String,Object> beanToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if(null == obj) {
            return map;
        }
        try {
            List<Method> methods = new ArrayList<>();
            Class<?> clazz = obj.getClass();
            while (!clazz.getName().equals("java.lang.Object")) {
                methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
                clazz = clazz.getSuperclass();
            }

            for(Method m : methods) {
                if(!m.getName().startsWith("get")) {
                    continue;
                }
                String propertyName = firstLetterToLower(m.getName().substring(3));
                if(m.invoke(obj) == null || "".equals(m.invoke(obj))) {
                    continue;
                }
                if("java.time.LocalDateTime".equals(m.getReturnType().getName())) {
                    LocalDateTime dateTime = (LocalDateTime) m.invoke(obj);
                    String dateStr = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
                    map.put(propertyName,dateStr);
                    continue;
                }
                map.put(propertyName,m.invoke(obj));
            }
        } catch (Exception ignored) {

        }
        return map;
    }

    private static String firstLetterToLower(String str) {
        char[] array = str.toCharArray();
        if (array[0] >= 'A' && array[0] <= 'Z') {
            array[0] += 32;
        }
        return String.valueOf(array);
    }
}
